<?php
$basedir = dirname($_SERVER['SCRIPT_FILENAME']) . DIRECTORY_SEPARATOR;
require($basedir . "feedcreator.class.php");
mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");
date_default_timezone_set("Europe/Moscow");
$now = time();
$timeout = 15*60;

if (isset($_GET['q'])) {
  	if (preg_match("#^si/fr/([0-9a-z]/[_0-9a-z]+)/([a-z0-9]+).xml\$#", $_GET['q'], $pcre)) {
  		$aid = $pcre[1];      // author's id
  		$feedtype = $pcre[2]; // feed type
// Look for cached file name
		$cfname = $basedir . "cache" . DIRECTORY_SEPARATOR . str_replace("/", "-", $aid) . ".$feedtype.xml";
		if (file_exists($cfname)) {
// Is file too old?
			$mtime = filemtime($cfname);
			$fage = $now - $mtime;
			if ($fage < $timeout) {
				header("Content-Type: application/xml; charset=utf-8");
				readfile($cfname);
			} else {
	  			generate_feed($aid, $feedtype, $cfname);
			}
		} else {
  			generate_feed($aid, $feedtype, $cfname);
		}
  	} elseif (preg_match("#^si/long/([a-z0-9]+).xml\$#", $_GET['q'], $pcre)) {
  		$feedtype = $pcre[1]; // feed type
// Look for cached file name
		$cfname = $basedir . "cache" . DIRECTORY_SEPARATOR . "long.$feedtype.xml";
		if (file_exists($cfname)) {
// Is file too old?
			$mtime = filemtime($cfname);
			$fage = $now - $mtime;
			if ($fage < $timeout) {
				header("Content-Type: application/xml; charset=utf-8");
				readfile($cfname);
			} else {
	  			generate_long_feed($feedtype, $cfname);
			}
		} else {
  			generate_long_feed($feedtype, $cfname);
		}
	} else {
		no_data();
	}
} else {
	no_data();
}

function generate_long_feed($feedtype, $cfname) {
// Connect to DB - currently hardcoded
	$mysqli = mysql_connect("localhost", "temmokan_dev", "myDevelopment");
	if (!mysql_select_db("temmokan_dev", $mysqli)) {
		no_data();
		exit(0);
	}
	if (mysql_errno()) {
		no_data();
		exit(0);
	}
	mysql_query("SET NAMES 'utf8'", $mysqli);
	mysql_query("SET CHARACTER SET utf8", $mysqli);
	mysql_query("SET COLLATION_CONNECTION = 'utf8_global_ci'", $mysqli); 
// 	Take up to 30*24 hours of everything starting from the topmost timestamp
	$sql = "SELECT MAX(`created`) as newest FROM si_news WHERE 1";
	$rc = mysql_query($sql, $mysqli);
	$row = mysql_fetch_assoc($rc);
	$newest = intval($row['newest']);
	$sql = "SELECT `url`,`author`, `title`, `size`, `created`, `categories` FROM si_news WHERE (`created`>=($newest-30*24*86400)) ORDER BY `created` DESC";
	$rc = mysql_query($sql, $mysqli);
// Generate feed
    $rss = new UniversalFeedCreator(); 
	$rss->encoding = "utf-8";
	while ($row=mysql_fetch_assoc($rc)) {
	    $item = new FeedItem(); 
   		$item->title = $row['author'] . ": " . $row['title']; 
   		$item->link = $row['url']; 
   		$item->description = $row['title'] . "; " . $row['categories'] . "; " . $row['size']; 
		$item->date = intval($row['created']); 
		$item->source = $item->link; 
		$item->author = $row['author']; 
		$rss->addItem($item); 
	}
	$rss->saveFeed("ATOM", $cfname);
}

function generate_feed($a, $f, $cfname) {
	if ($f != 'atom') {
		no_data(); exit(0);
	}
	$lt = localtime(); $lt[5] += 1900; $lt[4]++;
	$page = fetch_page("http://zhurnal.lib.ru/cgi-bin/frlist?DIR=$a");
	$lines = mb_split("[\r\n]", $page['contents']);
// Count
    $rss = new UniversalFeedCreator(); 
	$rss->encoding = "utf-8";
	$rss->title = "Новые работы авторов Самиздата"; 
	$rss->description = "новые работы авторов Самиздата за последние 30 дней";
// Scan the file    
    $fdata = array(
    	"author" => array(
    		"title" => "",
    		"url" => "http://zhurnal.lib.ru/cgi-bin/frlist?DIR=$a"
    	),
    	"entries" => array(
    	),
    );
    $namefound = false;
    for ($cnt = 0; $cnt < count($lines); $cnt++) {
    	if (!$namefound) {
    		if (strpos($lines[$cnt], "UNEXPECTED ERROR")) {
// Wrong URL - non-existent author
    			no_data(); exit(0);
			}
			if (mb_ereg("<center><h2><A HREF=/$a/>([^<]+)</a>", $lines[$cnt], $pcre)) {
				$fdata["author"]["title"] = $pcre[1];
				$namefound = true;
				$rss->title = $pcre[1] . ": лента друзей"; 
				$rss->description = "новые записи друзей автора " . $pcre[1];
			}
		}
		if (mb_ereg("<p><li>(.{5}) <a href=([^>]+)><font color=#555555>([^:]+):</font></a> <A HREF=([^>]+)><b>([^>]+)</b></A> &nbsp; <b>([^>]+)</b>(.*)</p>", $lines[$cnt], $pcre)) {
			$namefound = true;
			if (mb_ereg("<DD><font color=\"#555555\">([^>]+)</font>", $pcre[7], $pcre1)) {
				$teaser = $pcre1[1];
			} else {
				$teaser = '';
			}
			$fdata["entries"][] = array(
				"datetime" => $pcre[1],
				"authid" => $pcre[2],
				"authname" => $pcre[3],
				"link" => $pcre[4],
				"linkname" => $pcre[5],
				"size" => $pcre[6],
				"teaser" => $teaser,
			);
// Process date and time
			$dt1 = (int)substr($pcre[1], 0, 2);
			$dtsep = substr($pcre[1], 2, 1);
			$dt2 = (int)substr($pcre[1], 3, 2);
			if ($dtsep == ':') { // hour and minute
				$udate = 3*3600 + mktime($dt1, $dt2, 0, $lt[4], $lt[3], $lt[5]);
			} else { // day of month and month
				$udate = 3*3600 + mktime(12, 0, 0, $dt2, $dt1, $lt[5]);
			}
		    $item = new FeedItem(); 
    		$item->title = $pcre[3] . ": " . $pcre[5]; 
    		$item->link = "http://zhurnal.lib.ru" . $pcre[4]; 
    		$item->description = $teaser; 
			$item->date = $udate; 
			$item->source = $item->link; 
			$item->author = $pcre[3]; 
			$rss->addItem($item); 
		}
	}
//	var_dump($fdata);
	$rss->saveFeed("ATOM", $cfname);
}
  
function fetch_page($url) {
  	$rc = fetch_raw_page($url);
// If charset known, convert to UTF-8
  	if (($rc['header']['http_code'] == 200) && ($rc['err'] == 0)) {
  		if (preg_match("/charset=(.*)/", $rc['header']['content_type'], $pcre)) {
  			$iconv = $pcre[1];
  			$rc['contents'] = iconv($iconv, 'utf-8', $rc['contents']);
		}
	} else {
		$rc['contents'] = 'ERROR';
	}
	return $rc;
}
  
function fetch_raw_page($url) {
  	$rc = array();
    $ch = curl_init();
    
    $options = array(
        CURLOPT_URL => $url, // what to fetch
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.0.2) Gecko/2008092318 Fedora/3.0.2-1.fc9 Firefox/3.0.2", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );
    
// Set URL and other appropriate options
    curl_setopt_array( $ch, $options );
// Grab URL and pass it to the browser
	$rc['contents'] = curl_exec( $ch );
	$rc['err']      = curl_errno( $ch );
    $rc['errmsg']   = curl_error( $ch );
    $rc['header']   = curl_getinfo( $ch );
    
// Close cURL resource, and free up system resources
	curl_close($ch);  	
	return $rc;
}
  
function no_data() {
	echo "No valid data";
}
?>
